Examples: Variables and Data Types

The Interpreter


In [7]:
# The interpreter can be used as a calculator, and can also echo or concatenate strings.

3 + 3


Out[7]:
6

In [8]:
3 * 3


Out[8]:
9

In [9]:
3 ** 3


Out[9]:
27

In [10]:
3 / 2 # classic division - output is a floating point number


Out[10]:
1.5

In [11]:
# Use quotes around strings

'dogs'


Out[11]:
'dogs'

In [12]:
# + operator can be used to concatenate strings

'dogs' + "cats"


Out[12]:
'dogscats'

In [13]:
print('Hello World!')


Hello World!

Try It Yourself

Go to the section 4.4. Numeric Types in the Python 3 documentation at https://docs.python.org/3.4/library/stdtypes.html. The table in that section describes different operators - try some!

What is the difference betwee## Variables

Variables allow us to store values for later use. n the different division operators (/, //, and %)?

Variables

Variables allow us to store values for later use.


In [14]:
a = 5
b = 10
a + b


Out[14]:
15

Variables can be reassigned.


In [15]:
b = 38764289.1097
a + b


Out[15]:
38764294.1097

The ability to reassign variable values becomes important when iterating through groups of objects for batch processing or other purposes. In the example below, the value of b is dynamically updated every time the while loop is executed:


In [16]:
a = 5
b = 10
while b > a:
    print("b="+str(b))
    b = b-1


b=10
b=9
b=8
b=7
b=6

Variable data types can be inferred, so Python does not require us to declare the data type of a variable on assignment.


In [18]:
a = 5
type(a)


Out[18]:
int

is equivalent to


In [19]:
a = int(5)
type(a)


Out[19]:
int

In [20]:
c = 'dogs'
print(type(c))

c = str('dogs')
print(type(c))


<class 'str'>
<class 'str'>

There are cases when we may want to declare the data type, for example to assign a different data type from the default that will be inferred. Concatenating strings provides a good example.


In [21]:
customer = 'Carol'
pizzas = 2
print(customer + ' ordered ' + pizzas + ' pizzas.')


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-7975542f30cb> in <module>()
      1 customer = 'Carol'
      2 pizzas = 2
----> 3 print(customer + ' ordered ' + pizzas + ' pizzas.')

TypeError: must be str, not int

Above, Python has inferred the type of the variable pizza to be an integer. Since strings can only be concatenated with other strings, our print statement generates an error. There are two ways we can resolve the error:

  1. Declare the pizzas variable as type string (str) on assignment or
  2. Re-cast the pizzas variable as a string within the print statement.

In [22]:
customer = 'Carol'
pizzas = str(2)
print(customer + ' ordered ' + pizzas + ' pizzas.')


Carol ordered 2 pizzas.

In [23]:
customer = 'Carol'
pizzas = 2
print(customer + ' ordered ' + str(pizzas) + ' pizzas.')


Carol ordered 2 pizzas.

Given the following variable assignments:

x = 12
y = str(14)
z = donuts

Predict the output of the following:

  1. y + z
  2. x + y
  3. x + int(y)
  4. str(x) + y

Check your answers in the interpreter.

Variable Naming Rules

Variable names are case senstive and:

  1. Can only consist of one "word" (no spaces).
  2. Must begin with a letter or underscore character ('_').
  3. Can only use letters, numbers, and the underscore character.

We further recommend using variable names that are meaningful within the context of the script and the research.

Lists

https://docs.python.org/3/library/stdtypes.html?highlight=lists#list

Lists are a type of collection in Python. Lists allow us to store sequences of items that are typically but not always similar. All of the following lists are legal in Python:


In [1]:
# Separate list items with commas!

number_list = [1, 2, 3, 4, 5]
string_list = ['apples', 'oranges', 'pears', 'grapes', 'pineapples']
combined_list = [1, 2, 'oranges', 3.14, 'peaches', 'grapes', 99.19876]

# Nested lists - lists of lists - are allowed.

list_of_lists = [[1, 2, 3], ['oranges', 'grapes', 8], [['small list'], ['bigger', 'list', 55], ['url_1', 'url_2']]]

There are multiple ways to create a list:


In [2]:
# Create an empty list

empty_list = []

# As we did above, by using square brackets around a comma-separated sequence of items

new_list = [1, 2, 3]

# Using the type constructor

constructed_list = list('purple')

# Using a list comprehension

result_list = [i for i in range(1, 20)]

We can inspect our lists:


In [49]:
empty_list


Out[49]:
[]

In [50]:
new_list


Out[50]:
[1, 2, 3]

In [51]:
result_list


Out[51]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

In [52]:
constructed_list


Out[52]:
['p', 'u', 'r', 'p', 'l', 'e']

The above output for typed_list may seem odd. Referring to the documentation, we see that the argument to the type constructor is an iterable, which according to the documentation is "An object capable of returning its members one at a time." In our construtor statement above

# Using the type constructor

constructed_list = list('purple')

the word 'purple' is the object - in this case a word - that when used to construct a list returns its members (individual letters) one at a time.

Compare the outputs below:


In [53]:
constructed_list_int = list(123)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-53-b6b8bc4a05b6> in <module>()
----> 1 typed_list_int = list(123)

TypeError: 'int' object is not iterable

In [58]:
constructed_list_str = list('123')
constructed_list_str


Out[58]:
['1', '2', '3']

Lists in Python are:

  • mutable - the list and list items can be changed
  • ordered - list items keep the same "place" in the list

Ordered here does not mean sorted. The list below is printed with the numbers in the order we added them to the list, not in numeric order:


In [74]:
ordered = [3, 2, 7, 1, 19, 0]
ordered


Out[74]:
[3, 2, 7, 1, 19, 0]

In [75]:
# There is a 'sort' method for sorting list items as needed:

ordered.sort()
ordered


Out[75]:
[0, 1, 2, 3, 7, 19]

Info on additional list methods is available at https://docs.python.org/3/library/stdtypes.html?highlight=lists#mutable-sequence-types

Because lists are ordered, it is possible to access list items by referencing their positions. Note that the position of the first item in a list is 0 (zero), not 1!


In [77]:
string_list = ['apples', 'oranges', 'pears', 'grapes', 'pineapples']

In [78]:
string_list[0]


Out[78]:
'apples'

In [80]:
# We can use positions to 'slice' or selection sections of a list:

string_list[3:]


Out[80]:
['grapes', 'pineapples']

In [81]:
string_list[:3]


Out[81]:
['apples', 'oranges', 'pears']

In [82]:
string_list[1:4]


Out[82]:
['oranges', 'pears', 'grapes']

In [83]:
# If we don't know the position of a list item, we can use the 'index()' method to find out.
# Note that in the case of duplicate list items, this only returns the position of the first one:

string_list.index('pears')


Out[83]:
2

In [84]:
string_list.append('oranges')

In [86]:
string_list


Out[86]:
['apples', 'oranges', 'pears', 'grapes', 'pineapples', 'oranges']

In [85]:
string_list.index('oranges')


Out[85]:
1

In [ ]: